import React, { Component, PropTypes } from 'react'
import {Row,Col,Form,Select,Input,DatePicker,Table,Button,Modal,Tooltip,Icon,Transfer,message} from 'antd'
const createForm = Form.create;
const Option = Select.Option;
const FormItem = Form.Item;
const RangePicker = DatePicker.RangePicker;
import {WeaTop,WeaSearchForm,WeaInput4Hrm,WeaInput4Wf,WeaInput4Dep} from 'weaCom'

import Pro from 'promise'

const getDatas = (params) => {
	return new Pro((resolve,reject)=>{
		jQuery.ajax({
			type: "POST",
			url: "controller/ControlServlet.jsp?action=Action_DoFlowRequestDataGet",
			data: params,
			success: function(data) {
				//console.log("data:",data);
				//resolve(data);
				//v.splitTableHeadData(data.fl,data.ml);
				//v.splitPagingData(data.up);
				if(data && data.status && data.status==="false") {
					reject(data.error?data.error:"后端数据处理异常");
				}
				else {
		        	resolve(data);
		        }
			},
			error:function(data) {
				reject("后端AJAX异常");
				//reject(data);
			},
			dataType: "json"
		}); 
	});
}

const getFields = (params) => {
	return new Pro((resolve,reject)=>{
		jQuery.ajax({
			type: "POST",
			url: "controller/ControlServlet.jsp?action=Action_DoFieldListJsonGet",
			data: params,
			success: function(data) {
				if(data && data.status && data.status==="false") {
					reject(data.error?data.error:"后端数据处理异常");
				}
				else {
		        	resolve(data);
		        }
			},
			error:function(data) {
				reject("后端AJAX异常");
			},
			dataType: "json"
		});
	});
}

const setFields = (params) => {
	return new Pro((resolve,reject)=>{
		jQuery.ajax({
			type: "POST",
			url: "controller/ControlServlet.jsp?action=Action_DoFieldListSave",
			data: params,
			success: function(data) {
				if(data && data.status && data.status==="false") {
					reject(data.error?data.error:"后端数据处理异常");
				}
				else {
		        	resolve(data);
		        }
			},
			error:function(data) {
				reject("后端AJAX异常");
			},
			dataType: "html"
		});
	});
}

const getExcelDatas = (params) => {
	return new Pro((resolve,reject)=>{
		jQuery.ajax({
			type: "POST",
			url: "controller/ControlServlet.jsp?action=Action_DoFlowRequestDataExcelOut",
			data: params,
			success: function(data) {
				if(data && data.status && data.status==="false") {
					reject(data.error?data.error:"后端数据处理异常");
				}
				else {
		        	resolve(data);
		        }
			},
			error:function(data) {
				reject("后端AJAX异常");
			},
			dataType: "html"
		});
	});
}

class Main extends Component {
	constructor(props) { 
		super(props);
		this.state = {
			heads:[],
			datas:[],
			pageUtil:[],
			loading:true,
			order:"asc",
			visible:false,
			loadingCus:false,
			headFieldsWfId:"",
			headFields:[],
			targetKeys:[],
			loadingExcelOut:false,
			query:props.location.query
		}
	}
	componentDidMount() {
		const {query} = this.state;
		//console.log("query:",this.state.query);
		let that = this;
		const {setFieldsValue,getFieldsValue} = this.props.form;
		// setFieldsValue({
		// 	comId:query.comId
		// });
		let values = getFieldsValue();
		values.comId = query.comId || "";
		values.depId = query.depId || "";
		values.hrmId = query.hrmId || "";
		values.wfId = query.wfId || "";
		values.rlNum = "001";
		getDatas(values).then((data)=>{
			that.setState({
				heads:data.fl?data.fl:null,
				datas:data.ml?data.ml:[],
				pageUtil:data.up?data.up:{},
				loading:false
			});
		});
	}
	render() {
		let that = this;
		const {datas,pageUtil,loading,visible,loadingCus,headFields,headFieldsWfId,targetKeys,heads,loadingExcelOut} = this.state;
		const {getFieldProps,getFieldsValue,resetFields,getFieldValue} = this.props.form;
		let columns = [{
		title: '请求标题',
		dataIndex: 'requestTitle',
		key: 'requestTitle',
		width: 350,
		fixed: 'left',
		render(text,record,index) {
			return (
				<a target="_blank" href={"/workflow/request/ViewRequest.jsp?requestid="+record.requestId}>{text}</a>
			)
		}
		},{
		title: '流程编号',
		dataIndex: 'requestMark',
		key: 'requestMark',
		width: 250,
		fixed: 'left'
		},{
		title: '工作流',
		dataIndex: 'workflowName',
		key: 'workflowName',
		},{
		title: '节点',
		dataIndex: 'nodeName',
		key: 'nodeName',
		},{
		title: '创建人',
		dataIndex: 'createrName',
		key: 'createrName',
		render(text,record,index) {
			return (
				<a target="_blank" href={"/hrm/resource/HrmResource.jsp?1=1&id="+record.creater}>{text}</a>
			)
		}
		},{
		title: '审批人',
		dataIndex: 'approverName',
		key: 'approverName',
		render(text,record,index) {
			return (
				<a target="_blank" href={"/hrm/resource/HrmResource.jsp?1=1&id="+record.approver}>{text}</a>
			)
		}
		},{
		title: '耗时',
		dataIndex: 'cost',
		key: 'cost',
		width: 90,
		fixed: 'right',
		sorter:true
		},{
		title: '超时',
		dataIndex: 'overTime',
		key: 'overTime',
		width: 60,
		fixed: 'right'
		}];
		//console.log("heads:",heads);
		if(heads) {
			columns = new Array();
			for(let i=0;i<heads.length;i++) {
				const head = heads[i];
				let column = {
					title:head.cnName,
					dataIndex:head.enName,
					key:head.enName
				}
				if(head.enName=="requestTitle") {
					column.width = 350;
					column.fixed = "left";
				}
				if(head.enName=="requestMark") {
					column.width = 250;
					column.fixed = "left";
				}
				if(head.enName=="cost") {
					column.width = 90;
					column.fixed = "right";
				}
				if(head.enName=="overTime") {
					column.width = 60;
					column.fixed = "right";
				}
				columns.push(column);
			}
		}
		//console.log("columns:",columns);
		const pagination = {
			total: pageUtil.maxNum,
			current: pageUtil.nowPage,
			pageSize: pageUtil.pageNum,
			showSizeChanger: false,
			onShowSizeChange(current, pageSize) {
				console.log('Current: ', current, '; PageSize: ', pageSize);
			}
		};
		//console.log(columns.length*100);
		return (
			<Row>
			<Col style={{"minWidth":"950px","paddingLeft":"20px","paddingRight":"20px","paddingBottom":"20px"}}>
				<WeaTop title="流程自定义查询">
					<Button onClick={()=>{
						//console.log("history:",this.props.history);
						this.props.history.pushState(null,"/");
					}}>返回</Button>
				</WeaTop>
				<Form horizontal className="ant-advanced-search-form">
				<Row>
				<Col xs={8}>
					<FormItem
					label="流程类型"
					labelCol={{ span: 8 }}
					wrapperCol={{ span: 16 }}>
						<WeaInput4Wf {...getFieldProps("wfId")} isMult={true} />
					</FormItem>
					<FormItem
					label="节点类型"
					labelCol={{ span: 8 }}
					wrapperCol={{ span: 16 }}>
						<Select {...getFieldProps("nodetype")}>
							<Option value="">所有</Option>
							<Option value="0">创建</Option>
							<Option value="1">批准</Option>
							<Option value="2">提交</Option>
							<Option value="3">归档</Option>
						</Select>
					</FormItem>
					<FormItem
					label="请求编号"
					labelCol={{ span: 8 }}
					wrapperCol={{ span: 16 }}>
						<Input {...getFieldProps("requestmark")} />
					</FormItem>
					<FormItem
					label="接收日期"
					labelCol={{ span: 8 }}
					wrapperCol={{ span: 16 }}>
						<Col span="11">
							<FormItem>
								<DatePicker {...getFieldProps('getDateStart',{
									getValueFromEvent:(date,dateString)=>dateString
								})} format="yyyy-MM-dd" />
							</FormItem>
						</Col>
						<Col span="2">
							<p className="ant-form-split">-</p>
						</Col>
						<Col span="11">
							<FormItem>
								<DatePicker {...getFieldProps('getDateEnd',{
									getValueFromEvent:(date,dateString)=>dateString
								})} format="yyyy-MM-dd" />
							</FormItem>
						</Col>
					</FormItem>
				</Col>
				<Col xs={8}>
					<FormItem
					label="等级"
					labelCol={{ span: 8 }}
					wrapperCol={{ span: 16 }}>
						<Select {...getFieldProps("requestlevel")}>
							<Option value="">所有</Option>
							<Option value="0">正常</Option>
							<Option value="1">重要</Option>
							<Option value="2">紧急</Option>
						</Select>
					</FormItem>
					<FormItem
					label="请求标题"
					labelCol={{ span: 8 }}
					wrapperCol={{ span: 16 }}>
						<Input {...getFieldProps("requestitle")} />
					</FormItem>
					<FormItem
					label="创建人"
					labelCol={{ span: 8 }}
					wrapperCol={{ span: 16 }}>
						<WeaInput4Hrm {...getFieldProps("hrmId")} isMult={true} />
					</FormItem>
					<FormItem
					label="创建部门"
					labelCol={{ span: 8 }}
					wrapperCol={{ span: 16 }}>
						<WeaInput4Dep {...getFieldProps("depId")} isMult={true} />
					</FormItem>
				</Col>
				<Col xs={8}>
					<FormItem
					label="接收期间"
					labelCol={{ span: 8 }}
					wrapperCol={{ span: 16 }}>
						<Select {...getFieldProps("date2during")}>
							<Option value="0">所有</Option>
							<Option value="6">最近6个月</Option>
							<Option value="12">最近12个月</Option>
							<Option value="18">最近18个月</Option>
						</Select>
					</FormItem>
					<FormItem
					label="创建人编号"
					labelCol={{ span: 8 }}
					wrapperCol={{ span: 16 }}>
						<Input {...getFieldProps("workcode")} />
					</FormItem>
					<FormItem
					label="审批人"
					labelCol={{ span: 8 }}
					wrapperCol={{ span: 16 }}>
						<WeaInput4Hrm {...getFieldProps("userId")} isMult={true} />
					</FormItem>
					<FormItem
					label="创建日期"
					labelCol={{ span: 8 }}
					wrapperCol={{ span: 16 }}>
						<Col span="11">
							<FormItem>
								<DatePicker {...getFieldProps('createDateStart',{
									getValueFromEvent:(date,dateString)=>dateString
								})} format="yyyy-MM-dd" />
							</FormItem>
						</Col>
						<Col span="2">
							<p className="ant-form-split">-</p>
						</Col>
						<Col span="11">
							<FormItem>
								<DatePicker {...getFieldProps('createDateEnd',{
									getValueFromEvent:(date,dateString)=>dateString
								})} format="yyyy-MM-dd" />
							</FormItem>
						</Col>
					</FormItem>
				</Col>
				</Row>
				<Row>
				<Col span={12} offset={12} style={{ textAlign: 'right' }}>
					<Button type="primary" htmlType="submit" loading={loading} onClick={()=>{
						// that.setState({
						// 	loading:true
						// });
						// let values = getFieldsValue();
						// values.pageNum = 1;
						// //console.log('Submit!!!');
						// //console.log(values);
						// getDatas(values).then((data)=>{
						// 	that.setState({
						// 		heads:data.fl?data.fl:null,
						// 		datas:data.ml?data.ml:[],
						// 		pageUtil:data.up?data.up:{},
						// 		loading:false
						// 	});
						// });
						this.doSearch();
					}}>搜索</Button>
					<Button type="primary" loading={loadingExcelOut} onClick={()=>{
						this.setState({
							loadingExcelOut:true
						});
						let values = getFieldsValue();
						values.rlNum = "001";
						getExcelDatas(values).then((data)=>{
							window.open(data);
							this.setState({
								loadingExcelOut:false
							});
						});
					}}>导出</Button>
					<Button onClick={()=>{
						resetFields();
					}}>清除</Button>
					<Tooltip placement="top" title="选择流程类型后才可定制列！" mouseLeaveDelay={0.1}>
					<Button loading={loadingCus} disabled={!getFieldValue("wfId") || (getFieldValue("wfId") && getFieldValue("wfId").split(",").length>1)} onClick={()=>{
						that.setState({
							loadingCus:true
						});
						const wfId = getFieldValue("wfId");
						if(wfId!==headFieldsWfId) {
							getFields({wfId:wfId}).then((data)=>{
								//console.log("getFields:",data);
								that.setState({
									visible:true,
									loadingCus:false,
									headFields:data,
									headFieldsWfId:wfId
								});
							});
						}
						else {
							that.setState({
								visible:true,
								loadingCus:false,
							})
						}
					}}><span>定制列</span>
					</Button>
					</Tooltip>
				</Col>
				</Row>
				</Form>
				<div style={{"padding":"8px"}}>
					<Table onChange={(pagination, filters, sorter)=>{
						//console.log("sorter:",sorter);
						that.setState({
							loading:true
						});
						let values = getFieldsValue();
						values.rlNum = "001";
						if(sorter.columnKey) {
							if(sorter.columnKey==="cost") {
								if(sorter.order==="ascend") 
									values.order = "asc";
								else
									values.order = "desc";
							}
						}
						if(pagination.current) {
							values.pageNum = pagination.current;
						}
						getDatas(values).then((data)=>{
							that.setState({
								heads:data.fl?data.fl:null,
								datas:data.ml?data.ml:[],
								pageUtil:data.up?data.up:{},
								loading:false,
								order:values.order
							});
						});
						//console.log("filters:",filters," sorter:",sorter);

					}} scroll={{ x: columns.length*220 }} columns={columns} dataSource={datas} pagination={pagination} bordered loading={loading} />
				</div>
				<Modal title="定制列" visible={visible}
					onOk={()=>{
						// console.log("getFields:",getFields);
						// console.log("setFields:",setFields);
						setFields({
							wfId:headFieldsWfId,
							colValues:targetKeys.join(",")
						}).then((data)=>{
							// if(data=="1") {
							// 	message.error("定制列保存失败，请联系管理员！");
							// }
							// console.log("data:",data);
							that.setState({visible:false});
							that.doSearch();
						});
						
					}} 
					onCancel={()=>that.setState({visible:false})}>
					<AnalysisTransfer wfId={headFieldsWfId} datas={headFields} 
						setAnalysisTransfer={(tks)=>{
							//console.log("setAnalysisTransfer:",tks);
							that.setState({
								targetKeys:tks
							});
						}
					} />
		        </Modal>
			</Col>
			</Row>
		)
	}
	doSearch() {
		let that = this;
		this.setState({
			loading:true
		});
		const {getFieldsValue} = this.props.form;
		let values = getFieldsValue();
		values.pageNum = 1;
		//console.log('Submit!!!');
		//console.log(values);
		values.rlNum = "001";
		getDatas(values).then((data)=>{
			that.setState({
				heads:data.fl?data.fl:null,
				datas:data.ml?data.ml:[],
				pageUtil:data.up?data.up:{},
				loading:false
			});
		});
	}
}

class AnalysisTransfer extends Component {
	constructor(props) { 
		super(props);
		this.state = {
			mockData: [],
			targetKeys: [],
			wfIdOld: ""
		}
	}
	componentDidMount() {
		const {wfId,datas} = this.props;
		this.setDatas(wfId,datas);
	}
	componentWillReceiveProps(nextProps) {
		const {wfIdOld} = this.state;
		const {wfId,datas} = nextProps;
		if(wfIdOld!==wfId) {
			this.setDatas(wfId,datas);
		}
	}
	setDatas(wfId,datas) {
		// startArr:["请求标题","流程编号","工作流","节点","创建人"," 审批人 ","耗时","超时"],
		// startArrHidden:["请求编号","到达时间","审批时间","节点类型","创建公司","创建部门","审批公司","审批部门","是否退回","操作状态"],
		let mockData = new Array();
		let targetKeys = new Array();
		for(let i=0;i<datas.length;i++) {
			let data = datas[i];
			data.key = data.fieldId;
			if(data.enName!=="") {
				data.title = `${data.cnName}[${data.enName}]`;
			}
			else {
				data.title = `${data.cnName}`;
			}
			data.description = data.title;
			data.chosen = false;
			if(data.id!=="") {
				data.key = data.id;
				targetKeys.push(data.key);
			}
			else {
				data.key = "f"+data.detailNum+"_"+data.key;
			}
			mockData.push(data);
		}
		
		this.setState({
			mockData:mockData,
			targetKeys:targetKeys,
			wfIdOld:wfId
		});
		try {
			this.props.setAnalysisTransfer(targetKeys);
		}catch(e) {console.log(e);}
		
	}
	render() {
		const {mockData,targetKeys} = this.state;
		//console.log("mockData:",mockData);
		//console.log("targetKeys:",targetKeys);
		return (
			<Transfer
				listStyle={{
					width: 220,
					height: 300,
		        }}
				dataSource={mockData}
				showSearch
				targetKeys={targetKeys}
				onChange={
					(tks) => {
						//console.log("tks:",tks);
						this.setState({ targetKeys:tks });
						try {
							this.props.setAnalysisTransfer(tks);
						}catch(e) {console.log(e);}
					}
				}
				render={item => item.title}
			/>
		);
	}
}

Main = createForm()(Main);

export default Main